package com.example.denglu.config.exception;

import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

public class Errors {
    private static final Map<ErrorCode, HttpStatus> statusMap = new HashMap<>();

    public static void mapStatus(ErrorCode errorCode, HttpStatus httpStatus) {
        statusMap.put(errorCode, httpStatus);
    }

    public static HttpStatus mapStatus(ErrorCode errorCode) {
        return statusMap.getOrDefault(errorCode, HttpStatus.BAD_REQUEST);
    }

    public static BusinessException wrap(ErrorCode errorCode, Object... args) {
        return wrap(null, errorCode, args);
    }

    public static BusinessException wrap(Throwable cause) {
        if (cause instanceof BusinessException) {
            return (BusinessException) cause;
        }
        return wrap(cause, CommonError.SYSTEM_ERROR, cause.toString());
    }

    public static BusinessException wrap(Throwable cause, ErrorCode errorCode, Object... args) {
        BusinessException e = new BusinessException(getMessage(errorCode, args));
        return e;
    }

    public static String getMessage(ErrorCode errorCode, Object... args) {
        String s = errorCode.message();
        if (args != null) {
            s = String.format(s, args);
        }
        return s;
    }
}
